/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.command.account;

import apus.command.AbstractCommand;
import apus.entity.Account;
import apus.entity.Subscriber;
import apus.exception.BusinessException;
import apus.persistence.AbstractDAO;
import apus.persistence.AccountDAO;
import apus.persistence.OrganizationDAO;
import apus.persistence.PersonDAO;
import apus.services.ServiceLocator;
import java.util.Arrays;
import java.util.List;

/**
 * The <code>FindAccountBySubscriberCommand</code> class represents command 
 * to search accounts for subscriber.
 * @author  Maxim Vasilevsky
 * @author  Roman Dyatkovsky
 * @since APUS v0.4
 * @see AbstractCommand
 */
public class FindAccountsBySubscriberCommand <TypeEn extends Subscriber,TypeDAO extends AbstractDAO<TypeEn>> extends AbstractCommand{
    
    private Class<TypeDAO> clazz;
    private final static String OWNER_ID = "Owner";
    
    private final static String[] paramsNames = { OWNER_ID };
    
    public FindAccountsBySubscriberCommand(Class<TypeDAO> clazz, String name) {
        super(name);
        this.clazz=clazz;
    }
    
    @Override
    public void execute() {    
        int ID;
        String stringId = params.get(OWNER_ID);
        
        try{
            ID = Integer.parseInt(stringId);
        } catch(NumberFormatException e) {
            throw new BusinessException("Wrong ID format: "+stringId,e);
        }
        
        AccountDAO accDAO = ServiceLocator.getService(AccountDAO.class);
        AbstractDAO<TypeEn> subscriberDAO = ServiceLocator.getService(clazz);
        TypeEn entity = subscriberDAO.read(ID);
        
        if (entity==null){
            throw new BusinessException("Subscriber not found");
        }
        
        for(Account acc : accDAO.findAll()) {
            if ((acc.getSubscriber().getId()==ID)){
                System.out.println("ID=" + acc.getId() + " " + acc.toString());
            }
        }
    }
    
    @Override
    public List<String> getParamNames() {
        return Arrays.asList(paramsNames);
    }
    
    public static FindAccountsBySubscriberCommand getFindAccountsByPersonCommand(){
        return new FindAccountsBySubscriberCommand(PersonDAO.class, "Find accounts by person");
    }
    
    public static FindAccountsBySubscriberCommand getFindAccountsByOrganizationCommand(){
        return new FindAccountsBySubscriberCommand(OrganizationDAO.class, "Find accounts by organization");
    }
    
}
